/**
 * @description 微信中的支付中间页
 */
import style from './styles/App.less';
import classnames from "classnames";
import React from 'react';
import ShareOrPayLayer from "components/ShareOrPayLayer";
import util from "commons/util";
import { state } from "api_zhoujianyi/front/app/payment/pay/goods";
import { Toast, Dialog } from "wd-mobile";

const queryObject = util.parseQueryString();

// 检查支付状态
const checkPayState = function (options) {
    Toast.loading("", 50000);
    state({
        tradeNo: queryObject.tradeNo
    }).then(res => {
        Toast.destroy();
        // 出货成功
        if (res.data.goodsPayState == "GOODS_SUCCESS") {
            location.href = `./couponCode.html?tradeNo=${queryObject.tradeNo}`;
            return;
        }
        // 出货处理中
        if (res.data.goodsPayState == "GOODS_PENDING" && options.wait) {
            options.wait(res.data.firstRequest);
            return;
        }
        // 出货失败
        if (res.data.goodsPayState == "GOODS_FAILED" && options.fail) {
            Dialog.confirm("该订单支付失败，请重新购买。", "提示", undefined, {
                onOk: () => {
                    location.href = "./index.html";
                },
                onCancel: () => { },
                buttons: { "返回首页": true, '取消': false }
            });
            return;
        }
        // 如果有payAgain，则再去支付
        if (options.payAgain) {
            options.payAgain();
            return;
        }
        return true;
    })
}

// 页面可见后，查询支付状态
util.pageVisibleListener(function (isVisible) {
    if (isVisible) {
        // 检查支付状态
        checkPayState();
    }
})

if (!util.isWeixin() && !util.isDingTalk()) {
    // 检查支付状态
    checkPayState({
        wait: function (firstRequest) {
            if (firstRequest) {
                // 跳转支付链接
                location.href = decodeURIComponent(queryObject.payUrl);
            }
        }
    });
}

export const App = () => {
    return (
        <ShareOrPayLayer show={true} type="pay" payDone={() => {
            // 检查支付状态
            checkPayState({
                wait: function () {
                    // 点击继续支付，跳转支付链接
                    location.href = decodeURIComponent(queryObject.payUrl);
                }
            });
        }} payAgain={() => {
            // 检查支付状态
            checkPayState({
                payAgain: function () {
                    // 点击继续支付，跳转支付链接
                    location.href = decodeURIComponent(queryObject.payUrl);
                }
            });
        }} />
    )
}

export default App;